$(function(){
    // var domain = document.URL.match(/http[s]?:\/\/(.*?)([:\/]|$)/)[1].split('.');
    // if (domain.length - 1 === 2) {
    //     document.domain = domain[1] + '.' + domain[2];
    // }
    obj.init();
});

let obj = {
    dom: {
        tab: null,
        navMenu: null,
        // viewChange: null,
        mainDiv: null,
        // tabMenu: null,
        pwdChange: null,
        secretKey: null,
        downApp: null,
        homeSet: null
    },
    form : null,
    timer: null,
    init: function () {
        this.dom.navMenu    = $('.main-menu a[href]');
        // this.dom.viewChange = $('#bt_view_change');
        this.dom.mainDiv    = $('.padding-md');
        // this.dom.tabMenu    = $('#xh_tab_menu');
        this.dom.pwdChange  = $('#bt_ChangePwd');
        this.dom.secretKey  = $('#bt_refresh_secret');
        this.dom.downApp    = $('#bt_app_down');
        this.dom.homeSet    = $('#bt_homeSet');

        this.funObj().initTabs();
        this.funObj().checkSurvey();

        this.listener();
    },
    listener: function () {
        var $this = this;
        //页签/普通模式切换
        // $this.dom.viewChange.click(function () {
        //     $(this).find('> i').toggleClass('fa-circle').toggleClass('fa-circle-o');
        //     $this.funObj().changeViewMode($(this).find('> i').hasClass('fa-circle'));
        // }).trigger('click');
        //导航点击
        $this.dom.navMenu.click(function () {
            xhTop.createNewTab($.trim($(this).find('> span:first').text()), $(this).attr('href'), true);
            return false;
        });
        //只有一个功能则隐藏侧边栏，自动打开
        // if ($this.dom.navMenu.length === 1) {
        //     $('#sidebarToggleLG').trigger('click');
        //     $this.dom.navMenu.trigger('click');
        // }
        //更改密码
        $this.dom.pwdChange.click(function () {
            $this.funObj().changePwd();
        });
        //获取开发密钥
        $this.dom.secretKey.click(function () {
            $this.funObj().getSecretKey();
        }).trigger('click');
        //应用下载
        $this.dom.downApp.click(function () {
            $this.funObj().openAppDownPage();
        });
        //查看工资
        $('#bt_mine').click(function () {
            xhTop.createNewTab('个人中心', baseUrl + 'hrm/mine');
        });
        $this.dom.homeSet.click(function () {
            $this.funObj().homeSet();
        });
        //保持在线（30分钟）
        $this.funObj().keepAlive();
        $this.timer = setInterval(function () {
            $this.funObj().keepAlive();
        }, 1000 * 60 * 30);
    },
    funObj: function(){
        var $this = this;
        return {
            initTabs: function () {
                $this.dom.tab = $("#xh_top_tabs").nthTabs();
                $this.dom.tab.addTab({
                    id: 'xh_tab_home',
                    title:'首页',
                    content: "<iframe frameborder='0' style='width:100%;height: 100%;' src='" + baseUrl + "Home/index'></iframe>",
                    allowClose: false,
                    active: true
                });
            },
            changeViewMode: function (_useTab) {
                if (!_useTab) {
                    $this.dom.mainDiv.css('padding', '20px').html('<iframe name="iframe" src="' + baseUrl + 'Home/index" frameborder="0" style="width: 100%;height: 100%;"></iframe>');
                    return false;
                }
                // $this.dom.mainDiv.css('padding', '0px').html('<div id="xh_top_tabs" class="easyui-tabs" fit="true" style="width:100%;height:100%;"></div>');
                //渲染标签页，并添加右键菜单   打开首页
                // $('#xh_top_tabs').tabs({
                //     onContextMenu:function(e, title, index){
                //         e.preventDefault();
                //         if (title === '首页') {
                //             return false;
                //         }
                //         $this.dom.tabMenu.menu('show', {
                //             left: e.pageX,
                //             top: e.pageY
                //         }).data('tabTitle', title);
                //     }
                // }).tabs('add', {
                //     title: '首页',
                //     content: "<iframe frameborder='0'  style='width:100%;' src='" + baseUrl + "Home/index'></iframe>",
                //     closable: false,
                //     selected: true
                // });
                // $('.tabs-panels > .panel:last > .panel-body > iframe').css('height', '100%');
                //渲染右键菜单
                // $this.dom.tabMenu.menu({
                //     onClick : function (item) {
                //         $this.funObj().closeTab(this, item.name);
                //     }
                // });
            },
            homeSet: function () {
                window.top.xhTop.showModal({
                    title: '首页设置',
                    content: xhTool.getFrameString('home_set/userSet', {}, 430),
                    size: 'md',
                    width: 1200,
                    backClose: false,
                    button: '保存'
                });
            },
            changePwd: function () {
                window.top.swal.setDefaults({
                    showCancelButton: true,
                    cancelButtonText: '取消',
                    confirmButtonText: '下一步',
                    showLoaderOnConfirm: true,
                    allowOutsideClick: false,
                    progressSteps: ['1', '2']
                });
                var password = {},
                    steps    = [{
                        title: '输入原密码',
                        input: 'password',
                        preConfirm: function(oldPwd) {
                            return new Promise(function (resolve, reject) {
                                if (!oldPwd) {
                                    reject('密码不能为空！');
                                } else {
                                    password.oldPwd = oldPwd;
                                    $.ajax({
                                        url: baseUrl + 'Index/checkPassword',
                                        type: 'POST',
                                        data: password,
                                        complete: function(XMLHttpRequest){
                                            var result = XMLHttpRequest.responseJSON;
                                            if (!result || typeof result === 'string'){
                                                reject('请求失败！');
                                            }
                                            else if (result.error){
                                                reject(result.error);
                                            }
                                            else{
                                                resolve();
                                            }
                                        }
                                    });
                                }
                            })
                        }
                    },
                    {
                        title: '输入新密码',
                        confirmButtonText: '修改',
                        html: '<input type="password" id="new_pwd" class="swal2-input" placeholder="新密码" />' +
                        '<input type="password" id="confirm_pwd" class="swal2-input" placeholder="确认密码" >',
                        preConfirm: function() {
                            return new Promise(function (resolve, reject) {
                                var newPwd     = $('#new_pwd').val(),
                                    confirmPwd = $('#confirm_pwd').val();
                                if(newPwd.length < 6){
                                    reject('密码需大于6位数！');
                                } else if (newPwd !== confirmPwd) {
                                    reject('密码不匹配！');
                                } else {
                                    window.top.swal.resetDefaults();
                                    password.newPwd = newPwd;
                                    $.ajax({
                                        url: baseUrl + 'Index/changeSelfPwd',
                                        type: 'POST',
                                        data: password,
                                        complete: function(XMLHttpRequest){
                                            var result = XMLHttpRequest.responseJSON;
                                            if(xhExtra.checkError(result)) return false;
                                            window.top.xhTop.showMessage({type: 'success', title: result.msg});
                                        }
                                    });
                                    resolve();
                                }
                            })
                        }
                    }];
                window.top.swal.queue(steps)
                    .then(function(result) {window.top.swal.resetDefaults();}, function(dismiss) {window.top.swal.resetDefaults();});
            },
            closeTab: function (menu, type) {
                var tabTarget = $('#xh_top_tabs'),
                    allTabs = tabTarget.tabs('tabs'),
                    allTabTitle = [];
                $.each(allTabs, function (i, n) {
                    var opt = $(n).panel('options');
                    if (opt.closable) {
                        allTabTitle.push(opt.title);
                    }
                });
                var curTabTitle = $(menu).data('tabTitle'),
                    curTabIndex = tabTarget.tabs('getTabIndex', tabTarget.tabs('getTab', curTabTitle));
                switch (type) {
                    case 1://关闭当前
                        tabTarget.tabs('close', curTabIndex);
                        break;
                    case 2://全部关闭
                        for (var i = 0; i < allTabTitle.length; i++) {
                            tabTarget.tabs('close', allTabTitle[i]);
                        }
                        break;
                    case 3://除此之外全部关闭
                        for (var i = 0; i < allTabTitle.length; i++) {
                            if (curTabTitle !== allTabTitle[i]) {
                                tabTarget.tabs('close', allTabTitle[i]);
                            }
                        }
                        tabTarget.tabs('select', curTabTitle);
                        break;
                    case 4://当前侧面右边
                        for (var i = curTabIndex + 1; i < allTabTitle.length; i++) {
                            tabTarget.tabs('close', allTabTitle[i]);
                        }
                        tabTarget.tabs('select', curTabTitle);
                        break;
                    case 5: //当前侧面左边
                        for (var i = 0; i < curTabIndex; i++) {
                            tabTarget.tabs('close', allTabTitle[i]);
                        }
                        tabTarget.tabs('select', curTabTitle);
                        break;
                    case 6: //刷新
                        window.top.frames[curTabIndex].location.reload();
                        //var panel = tabTarget.tabs('getTab', curTabTitle).panel('refresh');
                        break;
                }
            },
            getSecretKey: function () {
                var listDom = $this.dom.secretKey.parents('#ul_secret_key');
                listDom.find('li:gt(0)').remove();
                var stateDom = $('<li><a href="#" class="clearfix">' +
                    '<div class="chat-detail m-left-sm">' +
                    '   <div class="chat-name">当前状态</div>' +
                    '   <div class="chat-message">刷新中...</div>' +
                    '</div>' +
                    '<div class="chat-status"><i class="fa fa-spinner fa-spin text-success"></i></div>' +
                    '</a></li>');
                listDom.append(stateDom);
                xhExtra.ajaxRequest('Index/getSecretKey', {}, {check: false}, function(result) {
                    if (result.error) {
                        stateDom.find('.chat-message').text(result.error);
                        return false;
                    }
                    listDom.find('li:gt(0)').remove();
                    listDom.append('<li><a href="#" class="clearfix">' +
                        '<div class="chat-detail">' +
                        '   <div class="chat-name">登陆码 - ' + result.hour + '时</div>' +
                        '   <div class="chat-message">' +
                        '       <img src="' + result.login + '" alt="登陆码" style="width:130px;height:130px;margin-top: 5px;">' +
                        '   </div>' +
                        '</div></a></li>');
                    listDom.append('<li><a href="#" class="clearfix">' +
                        '<div class="chat-detail">' +
                        '   <div class="chat-name">刷机码 - ' + result.hour + '时</div>' +
                        '   <div class="chat-message">' +
                        '       <img src="' + result.brush + '" alt="登陆码" style="width:130px;height:130px;margin-top: 5px;">' +
                        '   </div>' +
                        '</div></a></li>');
                    listDom.append('<li><a href="#" class="clearfix">' +
                        '<div class="chat-detail">' +
                        '   <div class="chat-name">刷机码（老） - ' + result.hour + '时</div>' +
                        '   <div class="chat-message">' +
                        '       <img src="' + result.brushOld + '" alt="登陆码" style="width:130px;height:130px;margin-top: 5px;">' +
                        '   </div>' +
                        '</div></a></li>');
                    // $.each(result.keys, function (time, key) {
                    //     listDom.append('<li><a href="#" class="clearfix">' +
                    //         '<div class="chat-detail m-left-sm">' +
                    //         '   <div class="chat-name">时间：' + time + ' 点</div>' +
                    //         '   <div class="chat-message">' + key + '</div>' +
                    //         '</div>' +
                    //         '<div class="chat-status"><i class="fa fa-circle-o text-success"></i></div>' +
                    //         '</a></li>');
                    // });
                });
            },
            openAppDownPage: function () {
                $('.sidebarRight-toggle').click();
                xhTop.showModal({
                    title: '应用下载',
                    content: xhTool.getFrameString('Appserver/schoolAppDown', null, 600),
                    backClose: false,
                });
            },
            checkSurvey: function () {
                xhExtra.ajaxRequest('index/checkSurvey', {}, {check: false}, function (data) {
                    if (data.error) {
                        return false;
                    }
                    window.top.swal({
                        title: '您有一份新问卷',
                        text: data[0].title,
                        type: 'info',
                        showCancelButton: true,
                        confirmButtonText: '立即填写',
                        cancelButtonText: '下次提醒'
                    }).then(function() {
                        window.top.xhTop.createNewTab('问卷填写', baseUrl + 'survey/');
                    }, function(dismiss) {});
                });
            },
            keepAlive: function () {
                xhExtra.ajaxRequest('index/keepAlive',
                    {
                        title: xhTop.getActiveTabName(),
                        url: xhTop.getActiveFrame().location.href
                    },
                    {check: false, success: false}
                );
            }
        }
    }
}
